package simonxianyu.learn.springmybatis.web;

import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import simonxianyu.learn.springmybatis.db.dbsvc.SysUserDbSvc;
import simonxianyu.learn.springmybatis.db.po.SysUser;
import simonxianyu.learn.springmybatis.util.PasswordEncoder;

import javax.servlet.http.HttpSession;

/**
 *
 * Created by simon on 2017/2/21.
 */
@Controller
public class LoginCtl extends BaseCtl {
  @Autowired
  private SysUserDbSvc dbSvc;
  @Autowired
  private PasswordEncoder passwordEncoder;

  @RequestMapping("/login")
  public ModelAndView loginForm() {
    return new ModelAndView("loginForm");
  }

  @RequestMapping("/doLogin")
  public ModelAndView doLogin(
      @RequestParam("userId") String userId, @RequestParam("password")String password,
      HttpSession session) {
    ModelAndView mav = new ModelAndView("login");
    SysUser user = dbSvc.getById(userId);
    if (null != user) {
      String encPassword = passwordEncoder.encode(password);
      if (StringUtils.equals(encPassword, user.getPassword())) {
        // Login success fully
        session.setAttribute(USER_ID, user.getLoginId());
        session.setAttribute(NICKNAME, user.getNickname());
        session.setAttribute(PARTNER_NO, user.getPartnerNo());
        mav.setViewName("redirect:/dashboard");

      }
    } else {
      mav.addObject("error", "user not found");

    }
    return mav;
  }

  @RequestMapping("/logout")
  public ModelAndView logout(HttpSession session) {
    session.removeAttribute(USER_ID);
    session.removeAttribute(NICKNAME);
    session.removeAttribute(PARTNER_NO);
    ModelAndView mav = new ModelAndView();
    mav.setViewName("redirect:/login");
    return mav;
  }
}
